<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="90px" style="margin-top: 20px;width: 85%;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名:" prop="username">
                        <el-input style="width: 240px" v-model="addForm.username" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号:" prop="phone_no">
                        <el-input style="width: 240px" v-model="addForm.phone_no" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12" v-if="!userId">
                    <el-form-item label="密码:" prop="password">
                        <el-input style="width: 240px" v-model="addForm.password" placeholder="默认密码为123456" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="在职:">
                        <el-switch style="margin-left: 10px;" v-model="addForm.is_on_job" active-color="#068CEE"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="允许登录:">
                        <el-switch style="margin-left: 10px;" v-model="addForm.is_login" active-color="#068CEE"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱:">
                        <el-input style="width: 240px" v-model="addForm.email" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系地址:">
                        <el-input style="width: 240px" v-model="addForm.address" placeholder="请输入" maxlength="100" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item>
                        <span slot="label"><i class="red_dot">*</i>分配角色:</span>
                        <div class="role_list">
                            <div class="item" v-for="item in roleLists" :key="'role_'+item.id">
                                <div class="titles"  @click="cellClick(item)"
                                    :style="{background: item.selected?'#068CEE':'#fff', color: item.selected?'#fff':'#333'}">
                                    <i :class="item.selected?'el-icon-check':''"></i>
                                {{ item.name }}</div>
                            </div>
                        </div>
                    </el-form-item>
                    <div v-if="!addForm.role.length" class="show_error">请分配角色</div>
                </el-col>
            </el-row>
        </el-form>
        
        <bottom-btns
            Width="70%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>
    </div>
</template>

<script>
import { registerAccount, updateUser, getUserList } from "@/api/user";
import { listRole } from '@/api/role';
import bottomBtns from "@/components/bottomBtns";

export default {
    name: 'userEdit',
    components: {
        bottomBtns
    },
    data() {
        return {
            userId: '',
            pageTitle: '',
            addForm: {
                username: '',
                phone_no: '',
                password: '123456',
                level: '二级账户',	
                corp_id: '',
                address: '',
                email: '',
                is_on_job: true,  //在职离职
                is_login: true,  //是否允许登录
                role: []
            },
            rules:{
                username: [
                    { required: true, message: "请输入用户名", trigger: "blur" },
                ],
                phone_no: [
                    { required: true, message: "请输入手机号", trigger: "blur" },
                ],
                password: [
                    { required: true, message: "请输入密码", trigger: "blur" },
                ],
            },
            roleLists: [],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ]
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    mounted() {
        this.addForm.corp_id = this.corpId
        this.userId = this.editId
        if (this.userId) {
            this.pageTitle = '编辑用户'
        }else{
            this.pageTitle = '新增用户'
        }
        this.getRoles()
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        // 角色列表
        getRoles() {
            listRole({page: 1, num: 9999}).then(res => {
                this.roleLists = res.data.data.role_list.filter(item => {
                    item.selected = false
                    return item
                })
                if (this.userId){
                    this.getUserInfo()
                }
            })
        },
        // 获取用户信息
        getUserInfo() {
            getUserList({corp: this.addForm.corp_id, id: this.userId}).then(res => {
                let list = res.data.users
                if (list.length){
                    this.addForm = list[0]
                    this.roleLists.forEach(item => {
                        if (list[0].role.length && list[0].role.includes(item.id)){
                            item.selected = true
                        }
                    })
                }
            })
        },
        cellClick(item) {
            item.selected = !item.selected
            this.addForm.role = this.handleRoles()
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        handleRoles() {
            let roles = []
            this.roleLists.forEach(item => {
                if (item.selected){
                    roles.push(item.id)
                }
            });
            return roles
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return

                that.addForm.role = that.handleRoles()
                if (!that.addForm.role.length) return

                let temp = null
                if (that.userId) {
                    temp = updateUser(that.userId, that.addForm)
                }else{
                    temp = registerAccount(that.addForm)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .red_dot {
        color: #ff4949;
        margin-right: 4px;
    }
    .show_error {
        color: #F56C6C;
        font-size: 12px;
        line-height: 1;
        padding-bottom: 20px;
        margin-left: 100px;
    }
    .role_list {
        // padding: 0 12px;
        padding-top: 15px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        .item {
            width: 28%;
            height: 44px;
            margin-bottom: 20px;
            // text-align: center;
            .titles {
                width: 160px;
                text-align: center;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                cursor: pointer;
            }
        }
    }
</style>